package com.ktwlsoft.archivemanage.domain.business.repositoryService.mend;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.ktwlsoft.archivemanage.domain.business.businessService.BasisBusinessManageService;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.AccountRepositoryService;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.OperationRepositoryService;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.businessInspect.BusinessInspectRepositoryService;
import com.ktwlsoft.archivemanage.domain.dao.entity.Account;
import com.ktwlsoft.archivemanage.domain.dao.entity.BasisBusinessManage;
import com.ktwlsoft.archivemanage.domain.dao.entity.Imgs;
import com.ktwlsoft.archivemanage.domain.dao.entity.OperationLog;
import com.ktwlsoft.archivemanage.domain.dao.entity.businessInspect.BusinessInspect;
import com.ktwlsoft.archivemanage.domain.dao.entity.mend.MendList;
import com.ktwlsoft.archivemanage.domain.dao.repository.IImgsMapper;
import com.ktwlsoft.archivemanage.domain.dao.repository.mend.MendListMapper;
import com.ktwlsoft.archivemanage.payload.guiBusiness.BasisBusinessManageRequest;
import com.ktwlsoft.archivemanage.payload.mendList.*;
import com.ktwlsoft.archivemanage.payload.operationLog.SaveLogRequest;
import com.ktwlsoft.archivemanage.service.security.UserPrincipal;
import lombok.Getter;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Component
public class MendListRepositoryService {

    @Getter
    private final MendListMapper mendListMapper;

    @Getter
    private final IImgsMapper imgsMapper;

    /**依据*/
    private final BasisBusinessManageService basisBusinessManageService;

    /**账号业务层接口实现类*/
    private final AccountRepositoryService accountRepositoryService;

    private final BusinessInspectRepositoryService businessInspectRepositoryService;

    public MendListRepositoryService(MendListMapper mendListMapper, IImgsMapper imgsMapper, BasisBusinessManageService basisBusinessManageService, AccountRepositoryService accountRepositoryService, BusinessInspectRepositoryService businessInspectRepositoryService) {
        this.mendListMapper = mendListMapper;
        this.imgsMapper = imgsMapper;
        this.basisBusinessManageService = basisBusinessManageService;
        this.accountRepositoryService = accountRepositoryService;
        this.businessInspectRepositoryService = businessInspectRepositoryService;
    }

    /**
     * 生成整改单
     *
     * @param mendList
     * @return
     */
    public int generateMendList(MendList mendList) {
        return mendListMapper.insert(mendList);
    }

    /**
     * 查询分页
     *
     * @param pageRequest
     * @return
     */
    public PageInfo<MendList> findMendListPage(MendListPageRequest pageRequest,String type) {
        PageHelper.startPage(pageRequest.getPn(), pageRequest.getPageSize());
        // pageRequest.setInstructFrom(DateUtils.dayMinTime(pageRequest.getInstructFrom()));
        // pageRequest.setInstructTo(DateUtils.dayMaxTime(pageRequest.getInstructTo()));
        Account account = UserPrincipal.getCurrentUser();
        if("pc".equals(type)) {
            if (account != null && !"ADMIN".equals(account.getRoleName()) && !"管理员".equals(account.getRoleName())
                    && !"业务指导处长".equals(account.getRoleName()) && !"正副局长".equals(account.getRoleName())) {
                pageRequest.setInstructorId(String.valueOf(account.getId()));
                pageRequest.setAccountId(null);
            }
        }
        List<MendList> listList = mendListMapper.findByPage(pageRequest);
        return new PageInfo<>(listList);
    }

    /**
     * 查询详情
     *
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public MendListResponse findDetail(Long id) {
        MendListResponse response = mendListMapper.selectByPrimaryKey(id);
        List<MendSubjectResponse> subjects = mendListMapper.selectSubjectByMendId(id);
        response.setMendSubjectList(subjects);
        for (MendSubjectResponse subject : subjects) {
            List<MendOptionResponse> options = mendListMapper.selectOptionsBySubjectId(subject.getId());
            subject.setMendOptionResponseList(options);
            List<Imgs> subjectImgs = imgsMapper.findImagesListByBusinessId(subject.getId());
            subject.setImgs(subjectImgs);
            //依据
            List<BasisBusinessManageRequest> requestList = Lists.newArrayList();
            List<BasisBusinessManage> manageList = basisBusinessManageService.getRepositoryService().findList(BasisBusinessManage.builder().businessId(subject.getId()).basisType("default").build());
            if(manageList != null){
                manageList.forEach(basisValue->{
                    BasisBusinessManageRequest request = new BasisBusinessManageRequest();
                    BeanUtils.copyProperties(basisValue,request);
                    try {
                        request.setContent(new String(basisValue.getContent(),"UTF-8"));
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    requestList.add(request);
                });
            }
            subject.setBasisBusinessManages(requestList);
            //选项
            for (MendOptionResponse o : options) {
                List<Imgs> optImgs = imgsMapper.findImagesListByBusinessId(o.getId());
                o.setImgs(optImgs);
            }
        }
        Imgs imgs = new Imgs();
        imgs.setBusinessId(response.getId());
        imgs.setBusinessType("ADDITIONS");
        response.setAdditions(imgsMapper.findList(imgs));
        OperationRepositoryService.saveLog(new SaveLogRequest(
                OperationLog.OperationType.CHECK,
                "查看检查整改，指导单号：" + response.getGuidNum(),
                "检查整改",
                OperationLog.BusinessType.BUSINESS
        ));
        //指导员电话
        if(response.getInstructorId() != null) {
            Account account = accountRepositoryService.getById(response.getInstructorId());
            if(account != null){
                response.setInstructorPhone(account.getTeleNum());
            }
        }
        return response;
    }

    /**
     * 整改
     *
     * @param id           整改单Id
     * @param mendRemark   整改说明
     * @param verifyRemark 验证备注
     * @return
     */
    public int updateMendList(Long id, String mendRemark, String verifyRemark) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id",id);
        jsonObject.put("mendRemark",mendRemark);
        jsonObject.put("verifyRemark",verifyRemark);
        return mendListMapper.updateMendList(jsonObject);
    }

    public int verifyMend(Long mendId, MendList.MendState verifyPass, String mendAdvice, BigDecimal mendMark) {
        return mendListMapper.veryfyMend(mendId, verifyPass, mendAdvice, mendMark);
    }

    public int delete(Long mendId) {
        return mendListMapper.deleteByPrimaryKey(mendId);
    }

    public List<MendList> findMendListBefore(Long notifyPeriod,Date date) {
        return mendListMapper.findMendListBefore(notifyPeriod,date);
    }

    /**
     * 通过业务检查外键查询数据 on 2019/11/13 10:52
     *
     * @param inspectId inspectId
     * @return MendList
     */
    public MendList getByInspectId(Long inspectId) {
        return mendListMapper.getByInspectId(inspectId);
    }

    public MendList findById(Long mendId) {
        return mendListMapper.selectById(mendId);
    }

    public List<InstructorsResponse> getInstructorsByArchivistId(Long archivistId) {
        return mendListMapper.getInstructorsByArchivistId(archivistId);
    }
}
